package com.authine.cloudpivot.ext.applicationservice;

import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.constants.AppConst;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.OrderCustomerGoodsDto;
import com.authine.cloudpivot.ext.dto.OrderGoodsReturnsDto;
import com.authine.cloudpivot.ext.dto.PageObject;
import com.authine.cloudpivot.ext.dto.PurchaseOrderReturnDto;
import com.authine.cloudpivot.ext.enums.order.OrderGoodsReturnsStatusEnum;
import com.authine.cloudpivot.ext.utils.*;
import com.authine.common.json.JsonUtils;
import com.authine.hermes.app.launcher.response.SingleResponse;
import com.authine.hermes.app.launcher.service.ApplicationService;
import com.authine.mvp.app.launcher.common.TableHelper;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.dto.bo.response.BOList;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.util.CollectionUtils;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.authine.hermes.app.launcher.service.ApplicationServiceFoundation.CUSTOM_SERVICE;

@Slf4j
@Path("ReturnService")
public class ReturnService extends ApplicationService {


    private final TableHelper tableHelper = ApplicationContextUtils.getBean(TableHelper.class);

    private NamedParameterJdbcTemplate jdbcTemplate = ApplicationContextUtils.getBean(NamedParameterJdbcTemplate.class);

    /**
     * 退货中
     *
     * @param dto
     * @return
     */
    @Path("returnList")
    @POST
    @Operation(summary = "售后退款-退货中列表", tags = CUSTOM_SERVICE, description = "pageIndex、pageSize必填")
    public com.alibaba.cola.dto.SingleResponse<BOList> returnList(@Parameter OrderGoodsReturnsDto dto) {
        log.info("------------------------售后退款-退货中列表 returnList Param：{}------------------------", JSONObject.toJSONString(dto));
        if (null == dto.getPageIndex() || null == dto.getPageSize()) {
            return com.alibaba.cola.dto.SingleResponse.buildFailure("-1", "pageIndex、pageSize必填");
        }
        Map<String, Object> parameter = new HashMap<>();
        StringBuilder listSql = new StringBuilder();
        StringBuilder whereSql = new StringBuilder();
        StringBuilder countSql = new StringBuilder();
        listSql.append("select ");


        listSql.append(" customerOrderGood.id order_customer_goods_id,\n" +
                "\tcustomerOrder.id order_customer_id,\n" +
                "\tcustomerOrderGood.customer_organization_name,\n" +
                "\tvendorOrder.organization_name,\n" +
                "\tvendorOrder.id vendor_order_id,\n" +
                "\tcustomerOrderGood.order_customer_goods_status,\n" +
                "\tcustomerOrder.erp_po,\n" +
                "\tcustomerOrderGood.brand,\n" +
                "\tcustomerOrderGood.name,\n" +
                "\tcustomerOrderGood.spec,\n" +
                "\tgood_return.customer_amount,\n" +
                "\tgood_return.memo,\n" +
                "\tgood_return.quantity,\n" +
                "\tcustomerOrderGood.model,\n" +
                "\tcustomerOrderGood.createdTime");
        listSql.append(" from ordercenter.i_ordercenter_t_order_goods_returns good_return ");
        listSql.append(" LEFT JOIN ordercenter.i_ordercenter_t_order_customer  customerOrder on customerOrder.id =good_return.order_customer_id and customerOrder.deleted = 0");
        listSql.append(" LEFT JOIN ordercenter.i_ordercenter_t_order_customer_goods customerOrderGood ON customerOrderGood.id = good_return.order_customer_goods_id AND customerOrderGood.deleted = 0");
        listSql.append(" LEFT JOIN ordercenter.i_ordercenter_t_order_vendor vendorOrder on vendorOrder.id = customerOrderGood.order_vendor_id AND vendorOrder.deleted = 0");

        countSql.append("select count(*) from ordercenter.i_ordercenter_t_order_goods_returns good_return ");
        whereSql.append(" where good_return.deleted ='0' and good_return.order_goods_returns_status ='ReturnPending'");
        //拼接参数
        //客户订单商品序号
        if (StringUtils.isNotBlank(dto.getOrderCustomerGoodsId())) {
            List<String> orderCustomerGoodsIds = StringUtils.stringToListString(dto.getOrderCustomerGoodsId(), ";");
            whereSql.append(" and good_return.order_customer_goods_id in (:order_customer_goods_id) ");
            parameter.put("order_customer_goods_id", orderCustomerGoodsIds);
        }
        //客户订单序号
        if (StringUtils.isNotBlank(dto.getOrderCustomerId())) {
            List<String> orderCustomerIds = StringUtils.stringToListString(dto.getOrderCustomerId(), ";");
            whereSql.append(" and good_return.order_customer_id in (:order_customer_id) ");
            parameter.put("order_customer_id", orderCustomerIds);
        }
        //供应商订单序号
        if (StringUtils.isNotBlank(dto.getOrderVendorId())) {
            List<String> orderVendorIds = StringUtils.stringToListString(dto.getOrderVendorId(), ";");
            whereSql.append(" and good_return.order_vendor_id in (:order_vendor_id) ");
            parameter.put("order_vendor_id", orderVendorIds);
        }
        //客户名称
        if (StringUtils.isNotBlank(dto.getCustomerOrganizationName())) {
            whereSql.append(" and good_return.customer_organization_name like :customer_organization_name ");
            parameter.put("customer_organization_name", "%" + dto.getCustomerOrganizationName() + "%");
        }
        //供应商名称
        if (StringUtils.isNotBlank(dto.getVendorOrganizationName())) {
            whereSql.append(" and good_return.vendor_organization_name like :vendor_organization_name ");
            parameter.put("vendor_organization_name", "%" + dto.getVendorOrganizationName() + "%");
        }

        countSql.append(whereSql);
        listSql.append(whereSql);
        listSql.append(" order by good_return.createdTime desc");
        listSql.append(" limit " + dto.getPageIndex() * dto.getPageSize() + ", " + dto.getPageSize());
        log.info("------------------------售后退款-退货中列表 returnList listSql：{}------------------------parameter：{}", listSql, JsonUtils.toJson(parameter));
        List<Map<String, Object>> resultList = jdbcTemplate.queryForList(listSql.toString(), parameter);
        Integer count = 0;
        try {
            count = jdbcTemplate.queryForObject(countSql.toString(), parameter, Integer.class);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        StringBuffer sbVendor = new StringBuffer();
        StringBuffer rpCode = new StringBuffer();
        for (Map<String, Object> objectMap : resultList) {
            // 数量求和
            BigDecimal number = new BigDecimal("0.00");
            BigDecimal amount = new BigDecimal("0.00");
            List<PurchaseOrderReturnDto> purchaseOrderReturnModel = this.getPurchaseReturnInfo((String)objectMap.get("order_customer_goods_id"));
            for (PurchaseOrderReturnDto orderReturnModel : purchaseOrderReturnModel) {

                number = orderReturnModel.getNum().add(number);
                amount = orderReturnModel.getAmount().add(amount);

                String vendorName = orderReturnModel.getVendorName();
                if (StringUtils.isNotBlank(vendorName)){
                    sbVendor.append(vendorName);
                    sbVendor.append(",");
                }
                if (StringUtils.isNotBlank(orderReturnModel.getRpCode())){
                    rpCode.append(orderReturnModel.getRpCode());
                    rpCode.append(",");
                }
            }
            if (sbVendor.length() > 0){
                sbVendor.deleteCharAt(sbVendor.length() - 1);
            }
            if (rpCode.length() > 0){
                rpCode.deleteCharAt(rpCode.length() - 1);
            }
            objectMap.put("vendor_transfer_name",sbVendor.toString());

            //设置退款数量
            objectMap.put("purchase_order_return_num", number);
            objectMap.put("purchase_order_return_amount", amount);
            objectMap.put("rpCode", rpCode.toString());
            //设置可退数量
            objectMap.put("quantity_returnable", getRefundableNum((String)objectMap.get("order_customer_goods_id")));
        }
        //构建结果集
        BoResultFormat.resultFormat(resultList, "dfcn86rbdb0g");
        BOList bOList = new BOList();
        bOList.setData(resultList);
        bOList.setTotal(count);
        bOList.setSchemaCode("dfcn86rbdb0g");
        return com.alibaba.cola.dto.SingleResponse.of(bOList);
    }

    //可退数量：订单总数（t_order_customer_goods.quantity）-退未发货数量（t_order_customer_goods.quantity_return_not_shipped）-退已发货数量（t_order_customer_goods.quantity_return_shipped）
    public BigDecimal getRefundableNum(String orderCustomerGoodsId) {
        Map<String, Object> orderCustomerGoods = JdbcTemplateUtils.builder(ModelConst.T_ORDER_CUSTOMER_GOODS)
                .selectField("(quantity-ifnull(quantity_return_not_shipped, 0.0)-ifnull(quantity_return_shipped, 0.0)) as refundable_num")
                .eq("id", orderCustomerGoodsId).queryForMap();
        return CollectionUtils.isEmpty(orderCustomerGoods)?BigDecimal.ZERO: BigDecimalUtils.isNull(orderCustomerGoods.get("refundable_num"));
    }



    /**
     * 根据云平台订单商品号,查询转采供应商和RP采购单号，供应商，退款金额
     * @param orderGoodsId
     * @return
     */
    public List<PurchaseOrderReturnDto> getPurchaseReturnInfo(String orderGoodsId) {
        String sql = " SELECT " +
                " SUM( G.amount ) as amount," +
                " SUM( G.num ) as num," +
                " group_concat( DISTINCT tv.company_name , ',' )  as vendorName , " +
                " group_concat( DISTINCT M.po_code , ',' )  as rpCode , " +
                " group_concat( DISTINCT M.refund_reason , ',' )  as rpMemo ," +
                " group_concat( DISTINCT M.createdTime, ',' )  as rpTime " +
                " FROM " +
                " "+getTableName(ModelConst.T_MEMBER_PURCHASE_ORDER_GOODS)+" " +
                " AS G LEFT JOIN "+getTableName(ModelConst.T_MEMBER_PURCHASE_ORDER)+" AS M ON M.ID = G.member_purchase_order_id " +
                " LEFT JOIN "+getTableName(ModelConst.T_TRANSFER_ORDER_GOODS)+" AS T ON T.ID = G.transfer_order_goods_id " +
                " LEFT JOIN "+getTableName(ModelConst.T_TRANSFER_ORDER)+" AS o ON o.ID = T.transfer_order_id " +
                " Left join  "+getTableName(AppConst.SYSTEM_MANAGEMENT, ModelConst.T_TRANSFER_VENDOR)+" as tv on tv.id=M.vendor_id " +
                " WHERE " +
                " G.deleted = FALSE " +
                " AND o.order_type IS NULL " +
                " AND M.deleted = FALSE " +
                " AND M.is_rp = TRUE " +
                " AND M.member_purchase_order_status IN ( 2, 3, 4 ) " +
                " AND T.cloud_order_goods_id = ";
        if (null != orderGoodsId) {
            sql += orderGoodsId;
        }

        sql += " GROUP BY G.transfer_order_goods_id ";
        return JdbcTemplateUtils.queryForPOJOList(sql, new HashMap<>(), ModelConst.T_MEMBER_PURCHASE_ORDER_GOODS, PurchaseOrderReturnDto.class);
    }

    /**
     * 获取表名称
     *
     * @param schemaCode
     * @return
     */
    public String getTableName(String schemaCode) {
        return tableHelper.getTableName(schemaCode);
    }

    /**
     * 获取应用表名(可获取其他应用表名)
     *
     * @param appCode
     * @param schemaCode
     * @return
     */
    public String getTableName(String appCode, String schemaCode) {
        if (StringUtils.isBlank(appCode)) {
            return getTableName(schemaCode);
        }
        return String.format("%s.i_%s_%s", appCode.toLowerCase(), appCode.toLowerCase(), schemaCode.toLowerCase());
    }


}
